package com.tanhua.dubbo.api.impl;

import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.dubbo.api.UserLocationApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@Service(timeout = 10000000)
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveLocation(Long userId, Double latitude, Double longitude, String addrStr) {
        Query query = new Query(Criteria.where("userId").is(userId));

        if (!mongoTemplate.exists(query, UserLocation.class)) {
            // 如果不存在数据
            UserLocation userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setCreated(System.currentTimeMillis());
            // 参数1-经度，参数2-纬度
            userLocation.setLocation(new GeoJsonPoint(longitude, latitude));
            userLocation.setAddress(addrStr);
            userLocation.setUpdated(System.currentTimeMillis());
            mongoTemplate.save(userLocation);

        } else {
            // 如果存在数据
            Update update = new Update();
            update.set("location", new GeoJsonPoint(longitude, latitude));
            update.set("address", addrStr);
            update.set("updated", System.currentTimeMillis());

            mongoTemplate.updateMulti(query, update, UserLocation.class);
        }
    }

    @Override
    public List<Long> searchNear(Long userId, Long distance) {
        // 1.查询自己的地理位置
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        GeoJsonPoint location = userLocation.getLocation();

        // 创建半径对象
        Distance distanceObj = new Distance(distance / 1000, Metrics.KILOMETERS);

        // 2.画圆，参数1-圆心，参数2-半径
        Circle circle = new Circle(location, distanceObj);

        // 3.查询在圆圈内的用户地理位置
        Query query2 = new Query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocationList = mongoTemplate.find(query2, UserLocation.class);

        if (userLocationList != null && userLocationList.size() > 0) {
            List<Long> userIdList = new ArrayList<>();
            for (UserLocation ul : userLocationList) {
                userIdList.add(ul.getUserId());
            }
            return userIdList;
        }
        return null;
    }
}
